import {
    Component, ContentChild,  EventEmitter, Input, OnChanges, Output, SimpleChanges, TemplateRef,
    ViewChild
} from '@angular/core';
import $ from "jquery";

@Component({
    selector: 'endless-list',
    templateUrl: 'endless-list.html'
})
export class EndlessListComponent implements OnChanges {

    @Input() pageParam: EndlessListParams;

    @Input() isLoaded = false;
    @Input() dataSource: Array<any>;
    @ContentChild(TemplateRef) itemTemplate: TemplateRef<any>;

    @Output() scrollToBottom;
    @Output() scroll;
    @Input() containerStyle: any;
    @ViewChild('scroller') scroller: any;
    @Input() dataSources: any[];
    showGoUp = true;
    public isArriveBottom = false;
    public isLoadingData = false;

    constructor() {
        this.scrollToBottom = new EventEmitter<any>();
        this.scroll = new EventEmitter<any>();
    }

    vw(v: number) {
        return window.innerWidth * v / 100;
    }

    scrolling(e) {

        const element = this.scroller.nativeElement;
        const tail = element.scrollHeight - element.scrollTop - element.clientHeight;

        if(tail <= this.vw(13.89) && !this.isArriveBottom){
            this.isArriveBottom = true;
            this.scrollToBottom.emit();
        }else if(tail > this.vw(13.89)){
            this.isArriveBottom = false;
        }

    }

    ngAfterContentChecked() {
    }

    ngAfterViewInit() {
    }

    ngAfterViewChecked() {
    }

    ngOnChanges(changes: SimpleChanges) {

    }

    ngOnDestroy() {
    }

    public goUp() {
        const element = this.scroller.nativeElement;
        $(element).animate({
                scrollTop: 0
            },
            100,
            void 0);
        this.isArriveBottom = false;
    }

}

export class EndlessListParams {
    pageSize: number;
    pageNumber: number;

}
